# -*- coding: utf-8 -*-
from django.shortcuts import render, redirect
from django.http.response import JsonResponse
from django import forms
from django.views import View
from rbac import models
from utils.pagination import Pagination


class UserForm(forms.ModelForm):
	def __init__(self, *args, **kwargs):
		super().__init__(*args, **kwargs)
		for field in self.fields.values():
			field.widget.attrs = {'class': 'form-control'}

	class Meta:
		model = models.User
		fields = '__all__'

		error_messages = {
			'username': {'required': '必填项'},
			'password': {'required': '必填项'}
		}

		widgets = {
			'password': forms.PasswordInput,
		}

class User_list(View):
	'''用户列表'''

	def get(self, request):
		user_all = models.User.objects.all()
		page_obj = Pagination(len(user_all), request.GET.get('page'))
		page_html = page_obj.page_html
		user_list = user_all[page_obj.start:page_obj.end]
		return render(request, 'user/user_list.html', locals())


class User_lookRole(View):
	'''查看用户列表'''

	def get(self, request, pk):
		Role_all = models.User.objects.filter(pk=pk).first().roles.all()
		page_obj = Pagination(len(Role_all), request.GET.get('page'))
		page_html = page_obj.page_html
		role_list = Role_all[page_obj.start:page_obj.end]
		return render(request, 'role/role_list.html', locals())


class User_add(View):
	'''添加用户'''

	def get(self, request):
		user_form = UserForm()
		return render(request, 'user/user_add.html', locals())

	def post(self, request):
		user_form = UserForm(request.POST)
		if user_form.is_valid():
			user_form.save()
			return redirect('user_list')
		return render(request, 'user/user_add.html', locals())


class User_edit(View):
	'''编辑用户'''

	def get(self, request, pk):
		user_obj = models.User.objects.filter(pk=pk).first()
		user_form = UserForm(instance=user_obj)
		return render(request, 'user/user_edit.html', locals())

	def post(self, request, pk):
		user_obj = models.User.objects.filter(pk=pk).first()

		# 密码可为空，重写密码属性required=False
		class Edit_userForm(UserForm):
			password = forms.CharField(required=False)

		user_form = Edit_userForm(request.POST, instance=user_obj)
		if user_form.is_valid():
			# 密码为空的情况
			if request.POST.get('password') == '':
				username = request.POST.get('username')
				age = request.POST.get('age')
				email = request.POST.get('email')
				gender = request.POST.get('gender')
				phone = request.POST.get('phone')
				models.User.objects.filter(pk=pk).update(
					username=username,
					age=age,
					email=email,
					gender=gender,
					phone=phone
				)
			else:
				user_form.save()
			return redirect('user_list')
		return render(request, 'user/user_edit.html', locals())


class User_del(View):
	'''删除用户'''

	def post(self, request, pk):
		ret = {'status': 0, 'msg': '删除成功'}
		if not models.User.objects.filter(pk=pk).delete():
			ret['msg'] = '删除失败'
		return JsonResponse(ret)